from flask import request,jsonify
from pymongo import MongoClient
from bson import json_util
import re
import math
from product.mongodb import mongodb

class goodsService:
    #获取数据，或根据查询条件获取指定数据
    def getData(self,requests):
        reqForm = request.form
        paramsJson = {}
        if ('goods_id' in reqForm and '' != reqForm['goods_id']):
            paramsJson['goods_id'] = re.compile(reqForm['goods_id'])
        if ('goods_name' in reqForm and '' != reqForm['goods_name']):
            paramsJson['goods_name'] = re.compile(reqForm['goods_name'])
        if ('sales' in reqForm and '' != reqForm['sales']):
            paramsJson['sales'] = re.compile(reqForm['sales'])
        if ('normal_price' in reqForm and '' != reqForm['normal_price']):
            paramsJson['normal_price'] = re.compile(reqForm['normal_price'])
        page = int(request.form['page'])
        limit = int(request.form['limit'])
        conn = MongoClient(mongodb.ip, 27017)
        db = conn.pinduoduo
        goodsDB = db.goods
        data = list(goodsDB.find(paramsJson).skip((page - 1) * limit).limit(limit))
        count = len(list(goodsDB.find(paramsJson)))
        returnJson = {
            'code': 0,
            'msg': 'success',
            'limit' : limit,
            "count": count,
            "data": data,
            "page": page,
            'pages' : math.ceil(count/limit)
        }
        return json_util.dumps(returnJson)

    #根据商品ID获取单个商品数据
    def getOneData(self,gooods_id):
        conn = MongoClient(mongodb.ip, 27017)
        db = conn.pinduoduo
        goodsDetailDB = db.goodsDetail
        data = goodsDetailDB.find_one({'goods_id':int(gooods_id)})
        return json_util.dumps(data)